package com.atguigu.spzx.common.handler.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

//mp配置&自动填充处理
@Configuration
public class MybatisPlusConfig implements MetaObjectHandler {
    //分页拦截器配置
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(false);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        return mybatisPlusInterceptor;
    }
    //mp对一个对象新增时并且 有属性配置了自动填充时机为新增 才会回调
    //新增自动填充回调
    @Override
    public void insertFill(MetaObject metaObject) {
        //如果新增触发回调的对象有 指定属性 才设置属性值
        if(metaObject.hasSetter("createTime")){
            metaObject.setValue("createTime" , new Date());
        }
        if(metaObject.hasSetter("updateTime")){
            metaObject.setValue("updateTime" , new Date());
        }
    }
    //更新自动填充回调
    @Override
    public void updateFill(MetaObject metaObject) {
        if(metaObject.hasSetter("updateTime")){
            metaObject.setValue("updateTime" , new Date());
        }
    }
}
